#!/bin/bash

helpneeded="false"

if [ $# = 0 ]
then
  helpneeded="true"
fi

if [ "$1" = "-h" ]
then
  helpneeded="true"
fi


if [ "$1" = "--help" ]
then
  helpneeded="true"
fi

if [ "$1" = "--h" ]
then
  helpneeded="true"
fi


if [ "$1" = "-d" ]
then
  indir=$2
 else
	helpneeded="true"
fi

if [ "$helpneeded" = "true" ]
then
echo
echo "pxunziptp script"
echo
echo "Unpack the result (TransformParametersArchive.tgz) of pxziptp." 
echo "The archive is optionally deleted"
echo 
echo "Usage:"
echo
echo "pxunziptp -d <dir> [delete]"
echo
exit 64
fi

deleten=`echo $* | grep "delete"`
nowdir=`pwd`
cd $indir
tparchive="TransformParametersArchive.tgz"
ziptpbusy="ziptpbusy.txt"

if [ -e "$ziptpbusy" ]
then
  echo "A $ziptpbusy-file has been found in the following directory: $indir"
  echo "This probably means that px(un)ziptp is still running in this directory, or that something unexpected happened in a previous run of px(un)ziptp!"
  cd $nowdir
  exit 65
fi

# generate a lock file
> $ziptpbusy

if [ -e "$tparchive" ]
then

  echo
  echo "The following directory will be processed by unziptp: $indir"
  echo

  echo "Unpacking $indir/$tparchive"
  tar -xjf $tparchive
  
  if [ -n "$deleten" ]
  then
    echo "Removing $indir/$tparchive"
    rm $tparchive
  fi

fi  

# delete lock file
rm $ziptpbusy

cd $nowdir
echo "Ready!"

exit 0

